package com.starhub.api.docwriting.service.impl;

import com.starhub.api.docwriting.entity.WritingVersion;
import com.starhub.api.docwriting.service.WritingVersionService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.starhub.api.docarchive.dto.DocArchiveBaseDTO;
import com.starhub.api.docarchive.result.DocArchiveDealResult;
import com.starhub.api.docarchive.service.DocArchiveService;
import com.starhub.api.docarchive.vo.DocArchiveBaseVO;
import com.starhub.api.docwriting.dao.WritingRecordMapper;
import com.starhub.api.docwriting.dto.WritingRecordDTO;
import com.starhub.api.docwriting.entity.WritingRecord;
import com.starhub.api.docwriting.result.WritingRecordDealResult;
import com.starhub.api.docwriting.service.WritingRecordService;
import com.starhub.api.docwriting.vo.WritingRecordVO;
import com.starhub.common.security.util.SecurityUtils;
import com.starhub.common.sys.user.LoginUser;
import com.starhub.engine.generator.genid.IdGenerator;
import com.starhub.utils.Util;

import java.time.LocalDateTime;

/**   
 * 写作记录管理服务层
 * @version: V1.0
 * @author: liuhf
 * @time 2025-05-18
 */
@Service
public class WritingRecordServiceImpl extends ServiceImpl<WritingRecordMapper, WritingRecord> implements WritingRecordService {

    @Autowired
    private DocArchiveService docArchiveService;

    @Autowired
    private WritingVersionService writingVersionService;

    /**
     * 获取用户写作记录列表
     * @param userId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public Page<WritingRecordVO>  getWritingRecordsByUserId(Integer pageNum, Integer pageSize) {
        //获取当前用户
        LoginUser user = SecurityUtils.getCurrentUser();

        //分页查询
        Page<WritingRecord> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<WritingRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WritingRecord::getUserId, user.getUserId());
        wrapper.eq(WritingRecord::getDeleteType, 0);
        wrapper.orderByDesc(WritingRecord::getCreateTime);

        // 获取总数
        Long total = this.count(wrapper);
        page.setTotal(total);
        
        //查询
        Page<WritingRecord> recordPage = this.page(page, wrapper);

        //转换
        Page<WritingRecordVO> resultPage = new Page<>(pageNum, pageSize);
        BeanUtils.copyProperties(recordPage, resultPage, "records");
        resultPage.setRecords(recordPage.getRecords().stream()
                .map(this::convertToVo)
                .toList());
                
        return resultPage;
    }

    /**
     * 获取写作记录详情
     * @param id
     * @return
     */
    @Override
    public WritingRecordDealResult getWritingRecordById(Long id) {
        WritingRecordDealResult result = checkWritingRecord(id);
        if (!result.isSuccess()) {
            return result;
        }

        WritingRecord record = this.getById(id);
        WritingRecordVO writingRecord = convertToVo(record);
        return WritingRecordDealResult.success(id, writingRecord);
    }

    /**
     * 新建记录
     * @param dto
     * @return
     */
    @Override
    public WritingRecordDealResult createWritingRecord(WritingRecordDTO dto) {
        LoginUser user = SecurityUtils.getCurrentUser();
        //生成ID
        Long id = IdGenerator.generateId();
        WritingRecord record = new WritingRecord();
        BeanUtils.copyProperties(dto, record);
        record.setId(id);
        record.setWritingType(dto.getType());
        record.setUserId(Util.getLongValue(user.getUserId()));
        boolean success = this.save(record);
        if (success) {
            saveVersion(record);
            return WritingRecordDealResult.success(id);
        } else {
            return WritingRecordDealResult.fail("新建失败");
        }
    }

    /**
     * 更新记录
     * @param dto
     */
    @Override
    public WritingRecordDealResult updateWritingRecord(WritingRecordDTO dto) {
        // 1. 检查记录
        WritingRecordDealResult result = checkWritingRecord(dto.getId());
        if (!result.isSuccess()) {
            return result;
        }

        // 2. 更新记录
        WritingRecord record = new WritingRecord();
        BeanUtils.copyProperties(dto, record);
        record.setWritingType(dto.getType());
        record.setUserId(result.getWritingRecord().getUserId());
        boolean success = this.updateById(record);
        if (success) {
            saveVersion(record);
            return WritingRecordDealResult.success(dto.getId());
        } else {
            return WritingRecordDealResult.fail("更新失败");
        }
    }

    /**
     * 删除记录
     * @param id
     * @return
     */
    @Override
    public WritingRecordDealResult deleteWritingRecord(Long id) {
        // 1. 检查记录
        WritingRecordDealResult result = checkWritingRecord(id);
        if (!result.isSuccess()) {
            return result;
        }

        // 2. 删除记录
        WritingRecord record = new WritingRecord();
        record.setId(id);
        record.setDeleteType(1);
        boolean success = this.updateById(record);
        if (success) {
            return WritingRecordDealResult.success(id);
        } else {
            return WritingRecordDealResult.fail("删除失败");
        }
    }

    /**
     * 检查记录
     * @param id
     * @return
     */
    private WritingRecordDealResult checkWritingRecord(Long id) {
        LoginUser user = SecurityUtils.getCurrentUser();
        WritingRecord existingRecord = this.getById(id);
        // 检查记录是否存在
        if (existingRecord == null) {
            return WritingRecordDealResult.fail("记录不存在");
        }
        // 检查记录是否存在
        if (user == null || !(existingRecord.getUserId().toString()).equals(user.getUserId())) {
            return WritingRecordDealResult.fail("无权限删除该记录");
        }
        // 检查记录是否被删除
        if (existingRecord.getDeleteType() != null && existingRecord.getDeleteType() == 1) {
            return WritingRecordDealResult.fail("记录已被删除");
        }
        WritingRecordVO recordVO = new WritingRecordVO();
        BeanUtils.copyProperties(existingRecord, recordVO);
        recordVO.setId(id.toString());
        return WritingRecordDealResult.success(id, recordVO);
    }

    /**
     * 添加到知识库
     * @param id
     * @return
     */
    @Override
    public WritingRecordDealResult addToArchive(Long id) {
        // 获取写作记录
        WritingRecord record = this.getById(id);
        if (record == null) {
            return WritingRecordDealResult.fail("写作记录不存在");
        }

        // 检查权限
        LoginUser user = SecurityUtils.getCurrentUser();
        if (!Util.null2String(record.getUserId()).equals(user.getUserId())) {
            return WritingRecordDealResult.fail("无权限操作该记录");
        }

        // 检查是否已添加到知识库
        DocArchiveBaseVO archive = docArchiveService.getByWritingRecordId(id);
        if (archive != null) {
            // 创建知识库DTO
            DocArchiveBaseDTO archiveDTO = DocArchiveBaseDTO.builder()
                .id(Long.parseLong(archive.getId()))
                .userId(Util.getLongValue(user.getUserId()))
                .writingRecordId(id)
                .content(record.getContent())
                .title(record.getTitle())
                .writingType(record.getWritingType())
                .isShared(0)
                .build();

            // 更新知识库
            DocArchiveDealResult archiveResult = docArchiveService.updateDocArchive(archiveDTO);
            if (!archiveResult.isSuccess()) {
                return WritingRecordDealResult.fail("更新知识库失败：" + archiveResult.getMessage());
            }
        }else{
            // 创建知识库DTO
            DocArchiveBaseDTO archiveDTO = DocArchiveBaseDTO.builder()
                .userId(Util.getLongValue(user.getUserId()))
                .writingRecordId(id)
                .content(record.getContent())
                .title(record.getTitle())
                .writingType(record.getWritingType())
                .isShared(0)
                .build();

            // 保存为知识库
            DocArchiveDealResult archiveResult = docArchiveService.createDocArchive(archiveDTO);
            if (!archiveResult.isSuccess()) {
                return WritingRecordDealResult.fail("保存为知识库失败：" + archiveResult.getMessage());
            }
        }
        
        return WritingRecordDealResult.success(id);
    }

    /**
     * 转换为结果
     * @param record
     * @return
     */
    private WritingRecordVO convertToVo(WritingRecord record) {
        WritingRecordVO result = new WritingRecordVO();
        BeanUtils.copyProperties(record, result);
        result.setId(record.getId().toString());
        return result;
    }


    private WritingVersion saveVersion(WritingRecord record) {
        WritingVersion version = new WritingVersion();
        Long id = IdGenerator.generateId();
        version.setId(id);
        version.setTitle(record.getTitle());
        version.setContent(record.getContent());
        version.setKeywords(record.getKeywords());
        version.setRemark(record.getRemark());
        version.setDeleteType(0);
        version.setWritingType(record.getWritingType());
        version.setWritingId(record.getId());
        version.setUserId(record.getUserId());
        version.setCreateTime(LocalDateTime.now());
        writingVersionService.save(version);
        return version;
    }

} 